/**     
 * @Title: BCD8421Operater.java   
 * @Package com.xxx.jt808.utils   
 * @Description: TODO
 * @author weiwei 
 * @date 2017年8月24日 上午9:38:58   
 * @version V1.0     
 */
package com.xxx.jt808.utils;

/**
 * @ClassName: BCD8421Operater
 * @Description: BCD8421码工具类
 * @author weiwei
 * @date 2017年8月24日 上午9:38:58
 * 
 */
public class BCD8421Operater {

	/**
	 * @Title: bcd2String
	 * @Description: BCD字节数组===>String
	 * @param bytes
	 * @Reutrn String 十进制字符串
	 */
	public static String bcd2String(byte[] bytes) {
		if (null == bytes || bytes.length <= 0) {
			return null;
		}
		StringBuffer temp = new StringBuffer(bytes.length * 2);
		for (byte b : bytes) {
			// 高四位
			temp.append((b & 0xf0) >>> 4);
			// 低四位
			temp.append(b & 0x0f);
		}
		return temp.toString().substring(0, 1).equalsIgnoreCase("0") ? temp.toString().substring(1) : temp.toString();
	}

	/**
	 * @Title: string2Bcd
	 * @Description: 字符串==>BCD字节数组
	 * @param str
	 * @Reutrn byte[] BCD字节数组
	 */
	public static byte[] string2Bcd(String str) {
		if (null == str || str == "") {
			return null;
		}
		// 奇数,前补零
		if ((str.length() & 0x1) == 1) {
			str = "0" + str;
		}
		byte ret[] = new byte[str.length() / 2];
		byte bs[] = str.getBytes();
		for (int i = 0; i < ret.length; i++) {
			byte high = ascII2Bcd(bs[2 * i]);
			byte low = ascII2Bcd(bs[2 * i + 1]);
			ret[i] = (byte) ((high << 4) | low);
		}
		return ret;
	}

	private static byte ascII2Bcd(byte asc) {
		if ((asc >= '0') && (asc <= '9')) {
			return (byte) (asc - '0');
		} else if ((asc >= 'A') && (asc <= 'F')) {
			return (byte) (asc - 'A' + 10);
		} else if ((asc >= 'a') && (asc <= 'f')) {
			return (byte) (asc - 'a' + 10);
		} else {
			return (byte) (asc - 48);
		}
	}

	public static void main(String[] args) {
		byte[] bytes = { '7', 'e' };
		String str = bcd2String(bytes);
		System.out.println(str);
		byte[] bs = string2Bcd("7e01020007000003081192000433303831313932b87e");
		if (null != bs && bs.length > 0) {
			for (Byte b : bs) {
				System.out.print(b + "  ");
			}
		}
	}

}